﻿namespace MultipleMonitorVideo.Modules
{
    using System.Windows;
    using System.Windows.Controls;

    using Caliburn.Micro;

    using ViewModels;
    using Views;
    using Screen = System.Windows.Forms.Screen;

    public abstract class Module
    {
        protected Module(ModuleControlViewModel controlViewModel, int columnIndex)
        {
            this.ColumnIndex = columnIndex;
            this.ControlViewModel = controlViewModel;
            this.ControlView = controlViewModel.GetView() as UserControl;
        }

        public int ColumnIndex
        {
            get;
            private set;
        }

        public UserControl ControlView
        {
            get;
            private set;
        }

        public ModuleControlViewModel ControlViewModel
        {
            get;
            private set;
        }

        public Window Window
        {
            get;
            private set;
        }

        public Screen Screen
        {
            get;
            private set;
        }

        public void SetScreen(Screen screen)
        {
            if (this.Screen != null)
            {
                if (this.ControlViewModel != null)
                {
                    this.ControlViewModel.SetViewModel(null);
                }

                this.DestroyWindow();
            }

            this.Screen = screen;
            
            if (screen != null)
            {
                this.CreateWindow();

                if (this.ControlViewModel != null)
                {
                    this.ControlViewModel.SetViewModel(this.Window.DataContext as ViewModel);
                }
            }
        }

        protected abstract Window FactoryBuildWindow(Screen screen);

        private void CreateWindow()
        {
            this.Window = this.FactoryBuildWindow(this.Screen);
            this.Window.ShowMaximized();
        }

        private void DestroyWindow()
        {
            this.Window.Close();
        }
    }
}
